# -*- coding: utf-8 -*-

def _import_csv(table,file):
    import csv
    reader = csv.reader(file)
    colnames=None
    for line in reader:
        if not colnames:
            colnames=[x[x.find('.')+1:] for x in line]
            c=[i for i in range(len(line)) if colnames[i]!='id']
        else:
            items=[(colnames[i],line[i]) for i in c]
            table.insert(**dict(items))


def sip():
    form = SQLFORM(db.config, fields=['name','appkey','secret','url','v'])
    if form.accepts(request.vars, session):
        redirect(URL(r=request,f='index',vars={'flash': '新的内容添加完成～'}))
    return dict(
        form = form,
        )

def api():
    form = SQLFORM(db.api)
    if form.accepts(request.vars, session):
        response.flash = '新内容已添加～'
    return dict(
        form = form,
        )

def type():
    form = SQLFORM(db.type)
    if form.accepts(request.vars, session):
        response.flash = '新内容已添加～'
    return dict(
        form = form,
        )

def interface():
    form = SQLFORM(db.interface)
    if form.accepts(request.vars, session):
        response.flash = '新内容已添加～'
    return dict(
        form = form,
        )

def isp():
    form = SQLFORM(db.isp)
    if form.accepts(request.vars, session):
        response.flash = '新内容已添加～'
    return dict(
        form = form
        )

def system_a():
    form = SQLFORM(db.isp)
    if form.accepts(request.vars, session):
        response.flash = '新内容已添加～'
    return dict(
        form = form,
        )

def application_a():
    form = SQLFORM(db.isp)
    if form.accepts(request.vars, session):
        response.flash = '新内容已添加～'
    return dict(
        form = form,
        )

def upload():
    input = FORM(TABLE(
        TR("table name:", INPUT(_type="text", _name="table_name")),
        TR("input:", INPUT(_type="file", _name="upload")),
        TR("",INPUT(_type="submit", _value="上传")),
        ))
    if input.accepts(request.vars, session):
        response.flash = 'putok'
        name = request.vars.table_name
        _import_csv(db[name], request.vars.upload.file)
    return dict(
        input = input,
        )
